<?php

namespace App\Http\Controllers\Web;

use App\Constants\HttpCode;
use App\Constants\HttpReturn;
use App\Constants\HttpStatus;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Validator;

class BaseController extends Controller
{
    public $validated;
    public $request;


    public function __construct()
    {
        $this->request = app('request');
    }
    /***
     * 返回函数
     * @param $return
     * @return \Illuminate\Http\JsonResponse
     */
    private function myResponse($return,$code = HttpCode::CODE_OK)
    {
        return response()->json($return,$code);
    }


    /***
     * 统一返回函数
     * @param array $data
     * @param array $meta
     * @return mixed
     */
    public function doResponseReturn(?string $msg = '',array $data = []):JsonResponse
    {
        return $this->myResponse( HttpReturn::getParseCon(HttpStatus::OK,$msg,$data) ,HttpCode::CODE_OK);
    }

    /***
     * 错误返回函数
     * @param array $data
     * @param array $meta
     * @return mixed
     */
    public function doResponseErrorReturn($msg = ''):JsonResponse
    {
        return $this->myResponse( HttpReturn::getParseCon(HttpStatus::ERROR,$msg) ,HttpCode::CODE_BAD_REQUEST);
    }


    /**
     * 验证输入信息
     * @param  array $rules
     * @return response
     */
    public function validateInput($rules)
    {
        $requests = $this->request->all();

        $validator = Validator::make($requests, $rules);
        if ($validator->fails()) {
            return self::doResponseErrorReturn($validator->messages()->first());
        } else {
            $this->validated = array_intersect_key($requests, $rules);
            $this->validated = $requests ;
            return false;
        }
    }

    /*
    * @param Request $request
    * @param array $rules
    * @param array $messages
    * @param array $customAttributes
    * @return array
    * @throws ValidationException
    */
    public function validateMsg(array $rules, array $messages = [], array $customAttributes = [])
    {
        $requests = $this->request->all();

        $validator = Validator::make($requests, $rules, $messages, $customAttributes);

        if ($validator->fails()) {
            return self::doResponseErrorReturn($validator->messages()->first());
        }else{
            $this->validated = array_intersect_key($requests, $rules);
            $this->validated = $requests ;
            return false;
        }

    }
}
